﻿using System;
using System.IO;
using System.Web.Mvc;
using yiCommerce.Core.Helper.FileUploader;
using yiCommerce.Service.Pictures;

namespace yiCommerce.Areas.Admin.Controllers
{
    public class FineUploaderController : Controller
    {

        private IPictureService _pictureService;

        public FineUploaderController(IPictureService pictureService)
        {
            _pictureService = pictureService;
        }

        [System.Web.Mvc.HttpPost]
        public virtual FineUploaderResult UploadFile(FineUpload upload, string extraParam1, int picSize)
        {
            // asp.net mvc will set extraParam1 and extraParam2 from the params object passed by Fine-Uploader

            var dir = @"c:\upload\path";
            var tempFileName = Guid.NewGuid().ToString() + Path.GetExtension(upload.Filename);
            var filePath = Path.Combine(dir, tempFileName);
            try
            {
                upload.SaveAs(filePath);
                var fileBinary = new byte[upload.InputStream.Length];
                var fileStream = new FileStream(filePath,FileMode.Open,FileAccess.Read);

                 var r = new BinaryReader(fileStream);

                fileStream.Read(fileBinary, 0, fileBinary.Length);
                r.BaseStream.Seek(0, SeekOrigin.Begin);    //将文件指针设置到文件开

                fileBinary= r.ReadBytes((int)r.BaseStream.Length);
                //var memoryStream = new MemoryStream();
                //upload.InputStream.CopyTo(memoryStream);
                //var fileBinary= memoryStream.ToArray();




                var originalPicture = _pictureService.InsertPicture(fileBinary, upload.ContentType, null, true);
                var pictureUrl = _pictureService.GetPictureUrl(originalPicture.Id,  0,true);

                var newPic = _pictureService.Resize(originalPicture.Id, picSize);
                var newPicUrl = _pictureService.GetPictureUrl(newPic.Id, 0, true);


                return new FineUploaderResult(true, new { OriginalPictureId = originalPicture.Id, OriginalPictureUrl = pictureUrl, NewPictureId = newPic.Id, NewPictureUrl = newPicUrl });
            }
            catch (Exception ex)
            {
                return new FineUploaderResult(false, error: ex.Message);
            }

            // the anonymous object in the result below will be convert to json and set back to the browser
        }


        

    }
}
